import axios from 'axios';
import router from '../router/index';
import Qs from 'qs';
// axios.defaults.withCredentials = true;//允许跨域   
// axios.defaults.属性 = 属性名  axios的全局配置
// 创建axios实例对象
let service = axios.create({});
export default function (url, method, params, headType) {
    let data = {};
    console.log('111');
    // post
    if (method == "post") {
        console.log(111);
        // headers content-type   form  序列化 QS    mul json
        if (headType == 'form') {
            service.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
            data = Qs.stringify(params); //序列化
        } else if (headType == "mul") {
            service.defaults.headers["Content-Type"] = "multipart/form-data";
            data = params;
        } else {
            service.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
            data = params;
        }

    }
    // get
    if (method == 'get') {
        if (headType == 'form') {
            service.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
        }
        if (params) {
            // 参数 url?key=value&key=value  Qs 
            data = Qs.stringify(params);
            url += "?" + data;
        }

    }

    // 拦截器
    // 请求拦截
    service.interceptors.request.use(config => {
        console.log(1111);
        console.log(config); //对象
        console.log(config.url);
        // 前台有token才能向服务器发送test请求，如果没有请返回登录界面
        // localStorage.getItem('token');
        // 先去判断是不是test请求，如果是再去看有没有token 返回登录界面 $router.push('/login');
        // url  '/api/test'  test
        // 字符串截取  slice 
        console.log(config.url.slice(5));
        if (config.url.slice(5) == 'test') {
            if (!localStorage.getItem('token')) {
                router.push('/login');
            }
        }
        return config;
    })
    // 响应拦截
    service.interceptors.response.use(response => {
        //做一些逻辑操作
        return response;
    })
    return new Promise((resolve, reject) => {
        service({
            url,
            method,
            data
        }).then(res => {
            console.log(res);
            resolve(res);
        }).catch(err => {
            console.log(err);
            reject(err);
        })
    })
}